package autohome.wz.lib;

import autohome.wz.dbutil.DbManager;
import autohome.wz.model.AutoHomeNews;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with Administrator
 * DATE:2016/12/22
 * Time:13:39
 */
public class AutoHomeNewsHelper {

    private static Logger logger = Logger.getLogger(AutoHomeNewsHelper.class);

    /**
     * 汽车之家文章入库
     *
     * @param model AutoHomeNews
     * @return 是否成功
     */
    public static int Add(AutoHomeNews model) {
        int result = 0;
        if (model != null && !model.getTitle().equals("")) {
            String strTitle = model.getTitle().replace("?", "？");
            String STR_SQL_FIND_TITLE = "SELECT TOP 1 id from recommend_news_resource_pool_wz with(nolock) where title ='" + strTitle + "'";
            try {
                Connection conn = DbManager.getConnection();
                QueryRunner queryRunner = new QueryRunner();
                List<AutoHomeNews> list = queryRunner.query(conn, STR_SQL_FIND_TITLE, new BeanListHandler<AutoHomeNews>(AutoHomeNews.class));
                if (list == null || list.size() == 0) {
                    String STR_SQL_ADD = "INSERT INTO [dbo].[recommend_news_resource_pool_wz] ([biz_id] ,[biz_type] ,[title] ,[publish_time] ,[img_url],[graphic_img_list2],[index_detail] ,[cms_content_class],[cms_tags] ,[author] ,[content] ,[check_status],[cms_series_id] ,[duration] ,[videoid] ,[playurls],[playcount]) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                    Object[] params = {model.getBiz_id(), model.getBiz_type(), model.getTitle(), model.getPublish_time(), model.getImg_url(), model.getGraphic_img_list2(), model.getIndex_detail(), model.getCms_content_class(), model
                            .getCms_tags(), model.getAuthor(), model.getContent(), model.getCheckStatus(), model.getCms_series_id(), model.getDuration(), model.getVideoid(), model.getPlayurls(), model.getPlaycount()};
                    try {
                        result = queryRunner.update(conn, STR_SQL_ADD, params);
                        DbUtils.closeQuietly(conn);
                    } catch (SQLException e) {
                        logger.error(e.getMessage());
                        Common.showMessage("写入数据库异常;" + model.getTitle());
                    } finally {
                        DbUtils.closeQuietly(conn);
                    }
                }
            } catch (SQLException e) {
                logger.error("头条文章add入库失败:" + e.getMessage());
            } finally {

            }
        }
        return result;
    }

}